<template>
  <div class="main">
    <div class="title-wrap">
      <h3 class="title">生成地址</h3>
    </div>
    <!-- 生成数据的条件 -->
    <div class="condition">
      <el-form
        :model="form"
        label-position="left"
        ref="formRef"
        label-width="160px"
      >
        <el-form-item prop="areaName">
          <template v-slot:label>
            <div class="label">请选择城市:</div>
          </template>
          <el-cascader
            v-model="form.areaName"
            :options="addressOptions"
            placeholder="选择城市"
            separator="-"
          />
        </el-form-item>
        <el-form-item prop="hasUserName">
          <template v-slot:label>
            <div class="label">是否需要姓名:</div>
          </template>
          <el-checkbox label="随机姓名" v-model="form.hasUserName"></el-checkbox>
          <!-- <el-checkbox-group v-model="form.contType">
            <el-checkbox label="隶属街道" ></el-checkbox>
            <el-checkbox label="所在路" ></el-checkbox>
            <el-checkbox label="户号" ></el-checkbox>
            <el-checkbox label="随机姓名"></el-checkbox>
          </el-checkbox-group> -->
        </el-form-item>
        <el-form-item prop="num">
          <template v-slot:label>
            <div class="label">生成数量:</div>
          </template>
          <el-input
            v-model.number="form.num"
            style="width: 240px"
            placeholder="请输入生成数量"
          />
        </el-form-item>
      </el-form>
    </div>

    <div class="cont">
      <div class="input-box">
        <div class="textarea">
          <el-input
            v-model="communityCont"
            placeholder="请在此处粘贴小区名称,1行1个"
            type="textarea"
            :rows="14"
          />
        </div>

        <div class="btn-wrap">
          <el-button type="primary" @click="startCreate" :loading="resLoading"
            >开始生成</el-button
          >
        </div>
      </div>
      <div class="input-result">
        <div class="tip success-color">结果将在此处显示:<span v-if="resultList.length > 0">共生成数量{{ resultList.length }}条</span></div>
        <div class="result hidden-xs-only">
          <div class="result-item" v-for="item in resultList">
            {{ item }}
          </div>
        </div>
        <div class="btn-wrap">
          <el-button type="primary" @click="copyResult">点击复制</el-button>
        </div>
      </div>
    </div>

    <el-divider />
    <div class="fail" v-if="failResultList.length > 0">
      <div class="f-title">
        <el-text class="mx-1" size="large" type="danger"
          >以下小区获取数据失败，请检查小区名称是否正确（小区名称请以腾讯地图为准）</el-text
        >
      </div>
      <div class="f-list">
        <div class="fl-item" v-for="(item, index) in failResultList">
          {{ index + 1 }}.{{ item }}
        </div>
      </div>
    </div>
    <textarea id="copyInput" class="copy-textarea"></textarea>
  </div>
</template>
<script setup lang="ts">
// @ts-nocheck
import { onMounted, ref, onUnmounted, reactive } from 'vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { ipcRenderer } from 'electron'
import { proCityCountry } from './data/proCityCountry.js'
import { ipcGetCommunityDetail } from './utils/request.js'
import {
  randomUserName,
  randomFullRoomNum,
  randomNum,
  randomUnitNum,
  replaceNumToHanNum,
  replaceHanNumToNum
} from './utils/tools.js'
import { clipboard } from 'electron'
const resLoading = ref(false)
const formRef = ref(null)
const form = reactive({
  areaName: '',
  // contType:['隶属街道','所在路','户号','随机姓名']
  hasUserName: false,
  num: 1
})
const contTypeKv = {
  隶属街道: 'street',
  所在路: 'road',
  户号: 'houseNum',
  随机姓名: 'userName'
}
const resultList = ref([])
const failResultList = ref([])
const communityCont = ref('')
const contTypeValueList = ref([])
const addressOptions = ref([])
const communityWidthBuildNums = ref({})

// 生成的结果类型 empty没有街道没有路，street街道 road路
function getResultType() {
  let resultType = 'empty'
  // 随机生成结果类型
  let rNum = randomNum(0, 3)
  if (rNum === 0) {
    resultType = 'empty'
  } else if (rNum === 1) {
    resultType = 'street'
  } else if (rNum === 2) {
    resultType = 'road'
  }
  return resultType
}

function initAddressOptions() {
  addressOptions.value = proCityCountry.map((item) => {
    return {
      label: item.label,
      value: item.value,
      children: item.children.map((citem) => {
        return {
          label: citem.label,
          value: citem.value
        }
      })
    }
  })
}
function copyResult() {
  let result = resultList.value.join('\n')
  // let input = document.getElementById('copyInput')
  // input.value = result
  // input.select()
  // console.log('result:',result)
  clipboard.writeText(result)
  ElMessage.success('复制成功')
}

// 初始渲染进程监听函数

function initIpcListener() {
  // 获取当日数据库数据
  ipcRenderer.on('searchDataByDate', () => {})
}
function getContTypeValue(contType) {
  let tempValue = contTypeKv[contType]
  return tempValue
}
function formCommunityNameList() {
  let tCommunityNameList = communityCont.value.split('\n')
  tCommunityNameList = tCommunityNameList
    .map((item) => item.trim())
    .filter((item) => !!item)
  // 分开楼道和小区名
  let communityNameList = []
  communityWidthBuildNums.value = {}
  tCommunityNameList.forEach(item=>{
    let communityBuildData = item.split(/\s/)
    if(communityBuildData.length===2){
      let communityName = communityBuildData[0]
      communityNameList.push(communityName)
      
      communityWidthBuildNums.value[communityName] = communityBuildData[1]
      let communityName2 = replaceNumToHanNum(communityName)
      let communityName3 = replaceHanNumToNum(communityName)
      communityWidthBuildNums.value[communityName2] = communityBuildData[1]
      communityWidthBuildNums.value[communityName3] = communityBuildData[1]
    }else{
      communityNameList.push(item)
    }
  })
  
  return Array.from(new Set(communityNameList))
}
// 不需要街道和路
function simpleFormatSuccessData(communityNameList) {
  let hasUserName = false
  let hasHouseNum = false
  if (contTypeValueList.value.includes('userName')) {
    hasUserName = true
  }
  if (contTypeValueList.value.includes('houseNum')) {
    hasHouseNum = true
  }
  resultList.value = communityNameList.map((cName, index) => {
    let proName = form.areaName[0]
    let cityName = form.areaName[1]
    let pcc = ''
    if (
      proName === '北京市' ||
      proName === '天津市' ||
      proName === '重庆市' ||
      proName === '上海市'
    ) {
      pcc = cityName
    } else {
      pcc = proName + cityName
    }
    let temp = pcc + cName
    if (hasHouseNum) {
      temp += randomFullRoomNum()
    }
    if (hasUserName) {
      temp = randomUserName() + ' ' + temp
    }
    return temp
  })
}
// 需要街道和路
/**
  
  {
  "_id": "6641bcdf26ebb32a14a9bc28",
  "proName": "北京市",
  "cityName": "北京市",
  "countryName": "朝阳区",
  "countryCode": "110105",
  "townName": "东湖街道",
  "townCode": "110105044",
  "roadName": "河荫中路",
  "roadNum": "",
  "communityName": "望京西园1区",
  "roadAddress": "北京市朝阳区河荫中路望京西园1区",
  "streetAddress": "北京市朝阳区东湖街道望京西园1区",
  "streetRoadAddress": "北京市朝阳区东湖街道河荫中路望京西园1区",
  "detailAddress": "朝阳区望京西园1区(河荫中路南150米)",
  "gcj02_lng": "116.47687",
  "gcj02_lat": "40.00363",
  "__v": 0
}
   
 */
function formatSuccessData(successData) {
  let computedResultData = []

  successData.forEach((cDataItem) => {
    console.log('cDataItem:',cDataItem)
    for (let i = 0; i < form.num; i++) {
      let temp = ''
      let resultType = getResultType()
      // 没有街道和路
      if (resultType === 'empty') {
        temp =
          cDataItem.proName +
          cDataItem.cityName +
          cDataItem.countryName +
          cDataItem.communityName
      } else if (resultType === 'street') {
        temp = cDataItem.streetAddress
      } else if (resultType === 'road') {
        temp = cDataItem.roadAddress
      }
      let buildNumStr = communityWidthBuildNums.value[cDataItem.communityName]
      // 获取小区楼栋数
      let buildNumList = buildNumStr ? buildNumStr.split(/[-,，;；]/) : []
      temp += randomUnitNum(buildNumList)
      
      if (form.hasUserName) {
        temp = randomUserName() + ' ' + temp
      }
      computedResultData.push(temp)
    }
  })
  computedResultData = Array.from(new Set(computedResultData))
  resultList.value = computedResultData
}
async function startCreate() {
  if (!form.areaName) {
    ElMessage({
      message: '请选择城市',
      type: 'error'
    })
    return
  }
  if (!Number.isInteger(form.num)) {
    ElMessage({
      message: '生成数量不能为空，且必须是整数',
      type: 'error'
    })
    return
  }
  let communityNameList = formCommunityNameList()
  if (communityNameList.length === 0) {
    ElMessage({
      message: '请输入小区名称，1行1个',
      type: 'error'
    })
    return
  }
  
  let reqData = {
    areaName: form.areaName,
    communityNameList
  }
  let resData = await ipcGetCommunityDetail('/getCommunityDetail', reqData)
  // console.log('resData:',resData)
  if (resData.code === 0) {
    let successData = resData.data.success
    // console.log('resData.fail:',resData.data.fail)
    // console.log('typeof resData.fail:',typeof resData.data.fail)
    failResultList.value = resData.data.fail

    formatSuccessData(successData)
    ElMessage({
      message: '生成成功',
      type: 'success'
    })
  } else {
    ElMessage({
      message: '生成失败',
      type: 'error'
    })
  }
}

onMounted(() => {
  initAddressOptions()
  // 初始化监听函数
  initIpcListener()
  window.addEventListener('resize', () => {})
})
onUnmounted(() => {
  window.onresize = null
})
</script>

<style lang="scss" scoped>
.main {
  min-height: calc(100vh - 292px);
  margin: auto;
  padding: 0px 12px 12px;
  box-sizing: border-box;
  .title-wrap {
    padding-bottom: 0px;
    background-color: #eee;

    .title {
      font-weight: 600;
      font-size: 28px;
      color: #33333b;
      text-align: center;
      margin-left: auto;
      margin-top: 0px;
      margin-right: auto;
      max-width: 1100px;
      padding: 18px;
    }
    .sub-title {
      line-height: 32px;
      font-size: 18px;
      color: #47474f;
      max-width: 980px;
      margin: 0px auto 24px;
      text-align: center;
      font-weight: bold;
    }
  }
  .condition {
    font-size: 16px !important;

    .el-form {
      display: flex;
      flex-wrap: wrap;
      .el-form-item {
        flex-shrink: 0;
        margin-left: 20px;
        align-items: center;
        &.single-row {
          flex-basis: 100%;
        }
        .el-select {
          flex-shrink: 0;
        }
        .upload-file-name {
          margin-left: 10px;
          color: #666;
        }
      }
      .el-form-item {
        margin-bottom: 20px;
        ::v-deep(.el-form-item__label) {
          display: flex !important;
          align-items: center;
          justify-content: flex-start;
        }
      }
      .label {
        font-weight: bolder;
        color: #000;
        font-size: 16px;
      }
      .el-checkbox-group {
        display: flex;
        align-items: center;
      }
    }
  }
  .cont {
    background: #fff;
    display: flex;
    align-items: flex-start;
    border-radius: 16px;
    justify-content: center;
    flex-wrap: wrap;
    font-size: 16px !important;
    margin-top: 20px;
    .btn-wrap {
      display: flex;
      justify-content: flex-end;
      border-top: 1px solid #eee;
      padding: 10px;
    }
    .input-box {
      margin-bottom: 20px;
      width: calc(50% - 2px);
      min-width: 320px;
      border: 1px solid #eee;
      box-sizing: border-box;
      .textarea {
        height: 400px;
        padding: 20px;
        .el-textarea {
          height: 100%;
          :deep(.el-textarea__inner) {
            box-shadow: none;
            resize: none;
          }
        }
      }
    }
    .input-result {
      width: calc(50% - 2px);
      background: #f8f8f8;
      border: 1px solid #eee;
      box-sizing: border-box;
      min-width: 320px;
      margin-bottom: 20px;
      text-align: left;
      .tip {
        height: 39px;
        line-height: 40px;
        border-bottom: 1px solid #eee;
        padding: 10px;
      }
      .result {
        height: 360px;
        padding: 10px;
        overflow-y: scroll;
        .mobile-res-item {
          background: #fff;
          border-radius: 8px;
          padding: 20px;
          margin-bottom: 20px;
          box-sizing: border-box;
          .mri-group {
            margin-top: 16px;
            display: flex;
            align-items: flex-start;
            justify-content: flex-start;
            line-height: 16px;
            font-size: 14px;
            &:last-child {
              margin-bottom: 0;
            }
            .label {
              width: 80px;
              color: #333;
              flex-shrink: 0;
            }
            .value {
              text-align: left;
            }
          }
        }
      }
    }
  }
  .fail {
    margin-top: 20px;
    .f-list {
      margin-top: 10px;
      .fl-item {
        margin-top: 10px;
      }
    }
  }

  @media screen and (max-width: 640px) {
    .cont {
      .input-box {
        .textarea {
          height: 300px;
          overflow-y: scroll;
        }
      }
      .input-result {
        .result {
          height: auto;
          min-height: 360px;
        }
      }
    }
  }
}
.copy-textarea {
  position: absolute;
  top: -1000px;
  left: -1000px;
  visibility: hidden;
}
</style>
